//
//  YFSportStatisticsVC.m
//  SquashSpark
//
//  Created by Coollang on 2017/12/7.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFSportStatisticsVC.h"
#import "JCChart.h"
#import "YFSportAndSensorApi.h"
#import "YFStatisticsModel.h"
#import "NSAttributedString+RichText.h"
#import "NSString+Extension.h"
#import "MyNavigationViewController.h"

@interface YFSportStatisticsVC ()<JCBarChartDelegate>

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *toolBtns;
@property (strong, nonatomic) UIView *lineView;
@property (weak, nonatomic) IBOutlet UIView *cutLine;
@property (weak, nonatomic) IBOutlet JCBarChart *barChartView;
@property (weak, nonatomic) IBOutlet UILabel *totalSwingLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalDurationLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalCaloriesLabel;
@property (weak, nonatomic) IBOutlet UILabel *avgTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *bestResultLabel;

@property (nonatomic, strong) NSMutableArray <JCBarChartItem *> *weekItemArray;
@property (nonatomic, strong) NSMutableArray <JCBarChartItem *> *mouthItemArray;
@property (nonatomic, strong) NSMutableArray <JCBarChartItem *> *yearItemArray;

/** 周的分析数据 */
@property (nonatomic, strong) YFStatisticsModel *weekDataModel;
/** 月的分析数据 */
@property (nonatomic, strong) YFStatisticsModel *monthDataModel;
/** 年的分析数据 */
@property (nonatomic, strong) YFStatisticsModel *yearDataModel;

/** 当前展示的是哪个类型 */
@property (nonatomic, assign)kStatisticsModelType currentShowType;

@end

@implementation YFSportStatisticsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置初始数据
//    self.weekDataModel = [YFStatisticsModel StatisticsModelWithPrivateType:kStatisticsModelWeek page:1];
//    self.monthDataModel = [YFStatisticsModel StatisticsModelWithPrivateType:kStatisticsModelMonth page:1];
//    self.yearDataModel = [YFStatisticsModel StatisticsModelWithPrivateType:kStatisticsModelYear page:1];
    [self initCode];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    MyNavigationViewController *navVc = (MyNavigationViewController *)self.navigationController;
    navVc.hiddenSeparationLine = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    MyNavigationViewController *navVc = (MyNavigationViewController *)self.navigationController;
    navVc.hiddenSeparationLine = NO;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self setupBarChartV];
    [self refreshDataWithType:0];
    [self loadWeekDataPage:1];
    [self loadMonthDataPage:1];
    [self loadYearDataPage:1];
}

- (void)loadWeekDataPage:(NSInteger)page {
    __weak typeof(self) weakSelf = self;
    [YFStatisticsModel loadWeekDataWithPage:page completed:^(BOOL suceess, YFStatisticsModel *weekDataModel) {
        weakSelf.weekDataModel = weekDataModel;
        if (weakSelf.currentShowType == kStatisticsModelWeek) {
            [weakSelf refreshDataWithType:kStatisticsModelWeek];
        }
    }];
}
- (void)loadMonthDataPage:(NSInteger)page {
    __weak typeof(self) weakSelf = self;
    [YFStatisticsModel loadMonthDataWithPage:page completed:^(BOOL suceess, YFStatisticsModel *monthDataModel) {
        weakSelf.monthDataModel = monthDataModel;
        if (weakSelf.currentShowType == kStatisticsModelMonth) {
            [weakSelf refreshDataWithType:kStatisticsModelMonth];
        }
    }];
}
- (void)loadYearDataPage:(NSInteger)page {
    __weak typeof(self) weakSelf = self;
    [YFStatisticsModel loadYearDataWithPage:page completed:^(BOOL suceess, YFStatisticsModel *yearDataModel) {
        self.yearDataModel = yearDataModel;
        if (weakSelf.currentShowType == kStatisticsModelYear) {
            [weakSelf refreshDataWithType:kStatisticsModelYear];
        }
    }];
}

- (void)setWeekDataModel:(YFStatisticsModel *)weekDataModel {
    _weekDataModel = weekDataModel;
    _weekItemArray = [NSMutableArray array];
    NSArray *allWeekDay = @[@"Mon",@"Tue",@"Wed",@"Thur",@"Fri",@"Sat",@"Sun"];
    NSDictionary *weekDict = [NSString dictionaryWithJsonString:self.weekDataModel.dataJson];
    // 排序日期从小到大
    NSArray *keys = [weekDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *_Nonnull obj1, NSString *_Nonnull obj2) {
        return [obj1 compare:obj2] != NSOrderedAscending;
    }];
    NSArray *weekValues = weekDict.allValues;
    for (NSInteger i = 0; i < allWeekDay.count; i++) {
        JCBarChartItem *item = [JCBarChartItem new];
        item.key = allWeekDay[i];
        item.value = (weekValues.count == 7) ? [weekDict[keys[i]] floatValue]:0;
        item.color = [UIColor blueColor];
        item.selectColor = [UIColor yellowColor];
        [_weekItemArray addObject:item];
    }
}

- (void)initCode {
    _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 65, 2)];
    _lineView.backgroundColor = [UIColor yellowColor];
    [_cutLine addSubview:_lineView];
    _lineView.center = CGPointMake(((UIButton *)_toolBtns.firstObject).center.x, 0);
    self.navigationItem.title = @"My Status";
}

- (void)setMonthDataModel:(YFStatisticsModel *)monthDataModel {
    _monthDataModel = monthDataModel;
    _mouthItemArray = [NSMutableArray array];
    NSArray *allWeek = @[@"Week1",@"Week2",@"Week3",@"Week4",@"week5"];
    NSDictionary *monthDict = [NSString dictionaryWithJsonString:self.monthDataModel.dataJson];
    if ((monthDict.count >= 4)) {
        for (NSInteger idxM = 0;idxM < monthDict.allValues.count; idxM++) {
            JCBarChartItem *item = [JCBarChartItem new];
            item.key = [NSString stringWithFormat:@"Week%zd",(idxM + 1)];
            item.value = [monthDict.allValues[idxM] floatValue];
            item.color = [UIColor blueColor];
            item.selectColor = [UIColor yellowColor];
            [_mouthItemArray addObject:item];
        }
    }else {
        for (NSString *key in allWeek) {
            JCBarChartItem *item = [JCBarChartItem new];
            item.key = key;
            item.value = 0;
            item.color = [UIColor blueColor];
            item.selectColor = [UIColor yellowColor];
            [_mouthItemArray addObject:item];
        }
    }
}

- (void)setYearDataModel:(YFStatisticsModel *)yearDataModel {
    _yearDataModel = yearDataModel;
    _yearItemArray = [NSMutableArray array];
    NSArray *allMouth = @[@"Jan.",@"Feb.",@"Mar.",@"Apr.",@"May.",@"Jun.",@"Jul.",@"Aug.",@"Sept.",@"Oct.",@"Nov.",@"Dec."];
    NSArray *yearValues = @[];
    if (self.yearDataModel.dataJson != nil) {
        yearValues = [NSString dictionaryWithJsonString:self.yearDataModel.dataJson];
    }
    for (NSInteger idy = 0; idy < yearValues.count; idy++) {
        JCBarChartItem *item = [JCBarChartItem new];
        item.key = allMouth[idy];
        item.value = (yearValues.count == 12) ? [yearValues[idy] floatValue]:0;
        item.color = [UIColor blueColor];
        item.selectColor = [UIColor yellowColor];
        [_yearItemArray addObject:item];
    }
}

- (void)setupBarChartV{
    //设置代理
    _barChartView.delegate = self;//代理
    _barChartView.barWidth = 35;
    _barChartView.space = 20;
    _barChartView.barColor = UIColorFromHex(0x448DFF);
    _barChartView.barTapColor = kYellowGreenColor;
}
//刷新数据
- (void)refreshDataWithType:(NSInteger)type{
    switch (type) {
        case 0:{
            _barChartView.items = _weekItemArray.mutableCopy;
            [self setStatisticDataWithModel:self.weekDataModel];
        }
            break;
        case 1:{
            _barChartView.items = _mouthItemArray.mutableCopy;
            [self setStatisticDataWithModel:self.monthDataModel];
        }
            break;
        case 2:{
            _barChartView.items = _yearItemArray.mutableCopy;
            [self setStatisticDataWithModel:self.yearDataModel];
        }
            break;
        default:
            break;
    }
    self.currentShowType = type;
    [_barChartView stroke];
    // 更新其他的数据
}


- (void)setStatisticDataWithModel:(YFStatisticsModel *)dataModel {
    self.totalSwingLabel.text = @(dataModel.totalSwings).stringValue;
    
    UIFont *bigFont = kOpenSansFont(OpenSansRegular, 24);
    UIFont *smallFont = kOpenSansFont(OpenSansRegular, 12);
    NSInteger sportTime = (dataModel.totalDuration > 0)? dataModel.totalDuration:0;
    NSInteger hour = sportTime / 60;
    NSInteger minute = sportTime % 60;
    NSString *sportTimeStr = [NSString stringWithFormat:@"%zdh%zdm",hour,minute];
    self.totalDurationLabel.attributedText = [NSAttributedString attributedString:sportTimeStr subString:@[@(hour).stringValue,@"h",@(minute).stringValue,@"m"] colors:@[kTWhiteText] fonts:@[bigFont,smallFont,bigFont,smallFont]];
    
    NSInteger avgSportTime = (dataModel.avgDuration > 0) ? dataModel.avgDuration : 0;
    NSInteger avghour = avgSportTime / 60;
    NSInteger avgminute = avgSportTime % 60;
    NSString *avgsportTimeStr = [NSString stringWithFormat:@"%zdh%zdm",avghour,avgminute];
    self.avgTimeLabel.attributedText = [NSAttributedString attributedString:avgsportTimeStr subString:@[@(avghour).stringValue,@"h",@(avgminute).stringValue,@"m"] colors:@[kTWhiteText] fonts:@[bigFont,smallFont,bigFont,smallFont]];
    
    NSString *calorieStr = [NSString stringWithFormat:@"%zdcal",dataModel.totalCaroline];
    self.totalCaloriesLabel.attributedText = [NSAttributedString attributedString:calorieStr subString:@[@(dataModel.totalCaroline).stringValue,@"cal"] colors:@[kTWhiteText] fonts:@[bigFont,smallFont]];
    
    CGFloat speed = (dataModel.maxSpeed > 0) ? dataModel.maxSpeed:0;
    NSString *unitSubStr = NSLocalizedString(@"kph", @"km/h");
    if (![YFUserDefaults generalMetricSystemUnit]) {
        unitSubStr = @"mph";
        speed = [Common kmhToMph:speed];
    }
    NSString *speedSubStr = [NSString stringWithFormat:@"%0.f",speed];
    NSString *speedStr = [NSString  stringWithFormat:@"%0.f%@",round(speed),unitSubStr];
    self.bestResultLabel.attributedText = [NSAttributedString attributedString:speedStr subString:@[speedSubStr,unitSubStr] colors:@[kTWhiteText,kTWhiteText] fonts:@[bigFont,smallFont]];
    
    
}

- (IBAction)toolAction:(UIButton *)sender {
    for (UIButton *btn in _toolBtns) {
        btn.selected = NO;
    }
    sender.selected = YES;
    [UIView animateKeyframesWithDuration:.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeCubic animations:^{
        _lineView.center = CGPointMake(sender.center.x, 0);
    } completion:^(BOOL finished) {
        
    }];
    [self refreshDataWithType:sender.tag];
}

- (void)bar:(JCBarChart *)barChart didselected:(NSInteger)index{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
